require 'simply_mongo'

class EnterprisesController < ApplicationController

  def new
    render :text => "SHOW"
  end

  def create
    e = params[:enterprise]
    logger.debug(e)
    en = e[:name]
    ec = SimplyMongo.db['enterprises']
    id = BSON::ObjectId.new
    e[:_id] = id
    ec.insert(e)
    eid = ec.find_one({'_id' => id}, { :fields => [ '_id'] } )
    j = { :id => eid['_id'].to_s}
    render :text => j.to_json
  end

  def index
    ec = SimplyMongo.db['enterprises']
    c = ec.find()
    e = [ ]
    c.each { |ce| e.push(ce) }
    render :text => e.to_json
  end

  def show
    ec = SimplyMongo.db['enterprises']
    id = params['id']
    bid = BSON::ObjectId id
    one = ec.find_one({ '_id' => bid})
    if one.nil?
      render :text => { }.to_json
    else
      oid = one['_id']
      one['_id'] = oid.to_s
      render :text => one.to_json
    end
  end

  def update
    p = params.clone
    id = p.delete('id')
    bid = BSON::ObjectId id
    p['_id'] = bid
    ec = SimplyMongo.db['enterprises']
    ec.update({'_id' => bid}, p)
    render :text => "{ 'code': 'success'}"
  end

  def destroy
    id = params['id']
    bid = BSON::ObjectId id
    ec = SimplyMongo.db['enterprises']
    ec.remove({'_id' => bid})
    render :text => { :removed =>"removed"}
  end

end
